package com.android.entity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class News {
	private static final String TITLE = "title";
	private static final String ROWS = "rows";
	private static final String DESCRIPTION = "description";
	private static final String IMAGE_HREF = "imageHref";
	
	private String title;
	private List<NewsItem> itemList;
	
	public News(){
	}
	
	public void setTitle(String title){
		this.title = title;
	}
	
	public String getTitle(){
		return title;
	}
	
	public void setNewsItem(List<NewsItem> itemList){
		this.itemList = itemList;
	}
	
	public List<NewsItem> getNewsList(){
		return itemList;
	}
	
	public static News fromJsonToObj(String newsData) {	    
		try {
			JSONObject root = new JSONObject(newsData);
			String title = root.getString(TITLE);

			News news = new News();
			news.setTitle(title);

			JSONArray jsonArray = root.getJSONArray(ROWS);
			List<NewsItem> items = new ArrayList<NewsItem>();
			for (int i = 0; i < jsonArray.length(); ++i) {
				JSONObject item = jsonArray.getJSONObject(i);
				String itemTitle = item.getString(TITLE);
				String itemDescription = item.getString(DESCRIPTION);
				String itemImageUrl = item.getString(IMAGE_HREF);

				if ("null".equalsIgnoreCase(itemTitle)) {
					itemTitle = "";
				}

				if ("null".equalsIgnoreCase(itemDescription)) {
					itemDescription = "";
				}

				if ("null".equalsIgnoreCase(itemImageUrl)) {
					itemImageUrl = "";
				}

				if (itemTitle.isEmpty() && itemDescription.isEmpty()
						&& itemImageUrl.isEmpty()) {
					continue;
				}

				NewsItem newItem = new NewsItem();
				newItem.setTitle(itemTitle);
				newItem.setDescripton(itemDescription);
				newItem.setImageUrl(itemImageUrl);
				items.add(newItem);
			}
			
			news.setNewsItem(items);
			return news;
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return null;
	}
}
